package image_controller

import (
	"cloudpichost/conf"
	"cloudpichost/internal/model"
	img2 "cloudpichost/internal/model/img"
	"cloudpichost/internal/model/site"
	store2 "cloudpichost/internal/model/store"
	storeService "cloudpichost/internal/service/store"
	"cloudpichost/internal/service/user"
	"cloudpichost/pkg/util/page"
	"cloudpichost/pkg/util/str"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
)

func ImgListPage(c *gin.Context) {
	var siteEntity site.Entity
	conf := siteEntity.FindOne()
	c.HTML(http.StatusOK, "imgdata_list.html", gin.H{"conf": conf})
}

// 图片列表
func ImgListJson(c *gin.Context) {
	var imgShow []map[string]interface{}
	page, _ := strconv.Atoi(strings.TrimSpace(c.DefaultQuery("page", "1")))
	limit := strings.TrimSpace(c.DefaultQuery("limit", "10"))
	imgData, count := img2.GetImgDataByLimit(page, limit, user.GetUserId(c))
	for _, v := range imgData {
		imgShow = append(imgShow, str.Struct2Map(img2.List{
			Id:        v.Id,
			ImgUrl:    v.ImgUrl,
			CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
			Sizes:     str.SizeFormat(float64(v.Sizes)),
			Abnormal:  v.Abnormal,
		}))
	}
	c.JSON(http.StatusOK, model.LayuiResp{Code: 0, Msg: "", Count: count, Data: imgShow})
}

func ImgShowPage(c *gin.Context) {
	queryPage := page.GetQueryPage(c)
	imgdata, count := img2.GetImgData(queryPage, user.GetUserId(c))
	pageCount := 0
	if count > 0 {
		pageCount = (count / conf.Setting.PageSize) + 1
	}
	var imgStr []string
	for _, v := range imgdata {
		imgStr = append(imgStr, v.ImgUrl)
	}
	c.HTML(http.StatusOK, "img_gallery.html", gin.H{"img": imgStr, "pageCount": pageCount, "page": queryPage})
}

func DelImg(c *gin.Context) {
	id, err := strconv.Atoi(c.PostForm("id"))
	if err != nil {
		c.JSON(http.StatusOK, model.AjaxResp{ErrorMsg: err.Error(), ResultCode: -1})
		return
	}
	imgdataById := img2.GetImgdataById(id)
	if err := DelImgDomain(imgdataById); err != nil {
		c.JSON(http.StatusOK, model.AjaxResp{ErrorMsg: err.Error(), ResultCode: -1})
		return
	}
	c.JSON(http.StatusOK, model.AjaxResp{ResultCode: 200})
}

func DelImgList(c *gin.Context) {
	ids := c.PostFormArray("ids")
	imgs := img2.GetImgdataByArr(ids)
	for _, v := range imgs {
		if err := DelImgDomain(v); err != nil {
			c.JSON(http.StatusOK, model.AjaxResp{ErrorMsg: err.Error(), ResultCode: -1})
			return
		}
	}
	c.JSON(http.StatusOK, model.AjaxResp{ResultCode: 200})
}

func DelImgDomain(v img2.Entity) error {
	var imgEntity img2.Entity
	cloudType := store2.GetStoreStr(v.Source)
	csc := store2.GetStoreConfig("cloud_type", cloudType)
	config := storeService.GetConfigType(csc)
	private := false
	cs, err := storeService.NewCloudStoreWithConfig(config, csc.CloudType, private)
	if err != nil {
		fmt.Println(err)
		return err
	}
	fileName := str.GetStoreFileName(v.ImgUrl)
	if err := cs.IsExist(fileName); err != nil {
		return errors.New("文件不存在，是否更换了存储源？")
	}
	if err := cs.Delete(fileName); err != nil { // 删除store原图
		return err
	}
	if err := imgEntity.Delete(v.Id); err != nil { // 删除数据库
		return err
	}
	return nil
}
